<template>
  <basic-container>
    <avue-crud
      :option="option"
      :search.sync="search"
      :table-loading="loading"
      :data="data"
      :page.sync="page"
      :permission="permissionList"
      :before-open="beforeOpen"
      v-model="form"
      ref="crud"
      @row-update="rowUpdate"
      @row-save="rowSave"
      @row-del="rowDel"
      @search-change="searchChange"
      @search-reset="searchReset"
      @selection-change="selectionChange"
      @current-change="currentChange"
      @size-change="sizeChange"
      @refresh-change="refreshChange"
      @sort-change="sortChange"
      @on-load="onLoad"
    >
      <template slot="menuLeft">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="small"
          @click.stop="handleSave"
          >绑 定</el-button
        >
      </template>
      <template slot-scope="scope" slot="menu">
        <!-- <el-button
          icon="el-icon-edit"
          size="small"
          type="text"
          @click.stop="handleEdit(scope.row, scope.index)"
          >修 改
        </el-button> -->
        <el-button
          icon="el-icon-connection"
          size="small"
          type="text"
          @click.stop="handleTerminalUN(scope.row)"
          >终端解绑
        </el-button>
        <el-button
          icon="el-icon-picture-outline"
          size="small"
          type="text"
          v-if="scope.row.rpmNo == 'R00001'"
          @click.stop="getqrCodeUrl(scope.row.qrcodeUrl)"
          >查看二维码
        </el-button>
      </template>
    </avue-crud>
    <!-- 新建 -->
    <el-dialog
      :title="terminalDialog.text"
      top="1%"
      append-to-body
      :close-on-click-modal="false"
      :visible.sync="terminalDialog.visible"
      v-if="terminalDialog.visible"
      :before-close="dialogClose"
      ref="terDialog"
    >
        <el-form
          :model="cashierForm"
          :rules="cashierRules"
          ref="cashierForm"
          size="small"
          label-width="auto"
        >
        <el-row :gutter="20" v-if="!terminalRpstNo">
          <el-col :span="24">
            <div class="haruyuki-plr-40">
              <el-form-item label="收银员:" prop="rpstNo">
                <el-select
                  size="small"
                  class="haruyuki-width-100"
                  v-model="cashierForm.rpstNo"
                  placeholder="请选择收银员"
                  filterable
                  clearable
                >
                  <el-option
                    v-for="item in rpstOptions"
                    :key="item.rpstNo"
                    :label="item.rpstName"
                    :value="item.rpstNo"
                  >
                    <span style="float: left">{{ item.rpstName }}</span>
                    <span style="float: right; color: #8492a6; font-size: 13px;margin-right:30px">{{ item.rpstNo }}</span>
                  </el-option>
                </el-select>
              </el-form-item>
            </div>
          </el-col>
        </el-row>
        </el-form>
      <el-transfer
        class="haruyuki-width-100 haruyuki-flex-center"
        filterable
        :filter-method="filterMethod"
        filter-placeholder="请输入终端名称"
        :button-texts="['解绑终端', '绑定终端']"
        :titles="['未绑定终端', '已绑定终端']"
        v-model="terminalAllot"
        :data="terminalData"
      >
      </el-transfer>
      <span slot="footer" class="dialog-footer">
        <el-button
          @click="
            () => {
              terminalDialog.visible = false;
              cashierForm.rpstNo = '';
            }
          "
          >取 消</el-button
        >
        <el-button type="primary" v-preventClick @click="terminalSubmit"
          >确 定</el-button
        >
      </span>
    </el-dialog>

    <el-image-viewer
      style="z-index: 2048"
      v-if="payVoucherDialog"
      :on-close="
        () => {
          payVoucherDialog = false;
        }
      "
      :url-list="[rqUrlImage]"
    ></el-image-viewer>
    <el-dialog
      title="数据导入"
      append-to-body
      :visible.sync="excelBox"
      width="555px"
    >
      <avue-form
        :option="excelOption"
        v-model="excelForm"
        :upload-after="uploadAfter"
      >
        <template slot="excelTemplate">
          <el-button type="primary" @click="handleTemplate">
            点击下载<i class="el-icon-download el-icon--right"></i>
          </el-button>
        </template>
      </avue-form>
    </el-dialog>
    <!-- 二级密码 -->
    <el-dialog
      title="二级密码"
      append-to-body
      width="440px"
      :close-on-click-modal="false"
      v-if="twoPwdShow"
      :visible.sync="twoPwdShow"
      :before-close="handleCloseTwoPwd"
    >
      <el-form :model="towPwdForm" ref="towPwdForm" label-width="0" class="demo-ruleForm">
        <el-form-item
          label=""
          prop="towPwd"
          :rules="[
            { required: true,message: '二级密码不能为空', trigger: ['change','blur']},
            { pattern: /^[0-9]{6}$/, message: '二级密码由6位数字组成', trigger: ['change','blur']}
          ]"
          >
          <el-input show-password v-model.number="towPwdForm.towPwd" autocomplete="off" placeholder="输入二级密码"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="twoPwdSubmit()">确 定</el-button>
      </div>
    </el-dialog>
  </basic-container>
</template>

<script>
import {
  getDetail,
  add,
  update,
  getStoreBindTerminalPage,
  getStoreUNBindTerminalPage,
  getStaffBindTerminalPage,
  getStaffUNBindTerminalPage,
  staffBindTerminal,
  staffUNBindTerminal
} from "@/api/rb-service/terminal/terminal";
  // remove,
import {
  getList as getCashierList
} from "@/api/rb-service/posStaff/pos_staff";
import { mapGetters } from "vuex";
import { getToken } from "@/util/auth";
import { userHasInfo } from "@/api/rb-service/forgetPassword/forgetPassword";
import md5 from 'js-md5';

export default {
  components: {},
  data() {
    return {
      payVoucherDialog: false,
      rqUrlImage: [],
      form: {},
      query: {},
      search: {},
      loading: true,
      excelBox: false,
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0,
      },
      selectionList: [],
      option: {
        height: "calc(50vh - 50px)",
        calcHeight: 30,
        tip: false,
        border: true,
        index: true,
        selection: true,
        searchMenuSpan: 6,
        columnBtn: false,
        labelWidth: 100,
        addBtn: false, //取消表格 新建/添加
        editBtn: false,
        viewBtn: false,
        delBtn: false,
        viewTitle: "修 改",
        menuWidth: 250,
        column: [
          {
            label: "终端类型",
            prop: "rptName",
            type: "input",
            //sortable: true,
            overHidden: true,
            display: false,
          },
          {
            label: "终端类型",
            prop: "rptNo",
            type: "select",
            overHidden: true,
            //sortable: true,
            searchOrder: 1,
            hide: true,
            display: false,
            rules: [
              {
                required: true,
                message: "请输入类型",
                trigger: "blur",
              },
            ],
            props: {
              label: "rptName",
              value: "rptNo",
              desc: "rptNo",
            },
            filterable: true,
            dicData: [],
          },
          {
            label: "终端编号",
            prop: "rtNo",
            type: "input",
            search: true,
            //sortable: true,
            overHidden: true,
            display: false,
          },
          {
            label: "终端简称",
            prop: "rtName",
            type: "input",
            search: true,
            overHidden: true,
            display: false,
          },
          {
            label: "所属收银员",
            prop: "rpstName",
            type: "input",
            //sortable: true,
            display: false,
          },
          {
            label: "所属收银员",
            prop: "rpstNo",
            type: "select",
            //sortable: true,
            search: true,
            searchLabelWidth: 94,
            hide: true,
            filterable: true,
            display: false,
            // rules: [
            //   {
            //     required: true,
            //     message: "请输入收银员",
            //     trigger: "blur",
            //   },
            // ],
            props: {
              label: "rpstName",
              value: "rpstNo",
              desc: "rpstNo",
            },
            dicUrl: `/api/rb-service/service/posStaff/pos_staff/listV2?current=-1&size=-1`,
            dicFormatter: (data) => {
              return data.data.records;
            },
            // dicData: []
          },
          // {
          //   label: "SN",
          //   prop: "rsSn",
          //   type: "input",
          //   sortable: true,
          //   search: true,
          //   rules: [
          //     {
          //       required: true,
          //       message: "请输入SN",
          //       trigger: "blur",
          //     },
          //   ],
          // },
          {
            label: "绑定日期",
            prop: "createTime",
            type: "input",
            rules: [
              {
                required: true,
                message: "请输入SN",
                trigger: "blur",
              },
            ],
            display: false,
            overHidden: true,
            width:140,
          },
        ],
      },
      data: [],
      excelForm: {},
      excelOption: {
        submitBtn: false,
        emptyBtn: false,
        column: [
          {
            label: "模板上传",
            prop: "excelFile",
            type: "upload",
            drag: true,
            loadText: "模板上传中，请稍等",
            span: 24,
            propsHttp: {
              res: "data",
            },
            tip: "请上传 .xls,.xlsx 标准格式文件",
            action: "/api/rb-service/service/terminal/terminal/import",
          },
          {
            label: "模板下载",
            prop: "excelTemplate",
            formslot: true,
            span: 24,
          },
        ],
      },
      terminalDialog: {
        disabled: false,
        visible: false,
        type: "add",
        text: "",
      }, //表格右侧操作add,edit,view
      terminalAllot: [],
      terminalData: [],
      terminalRpstNo: '', //收银员编号
      cashierForm: {
        rpstNo: '', //收银员编号
      },
      cashierRules: {
        // rpstNo: [
        //   { required: true, message: "请选择收银员", trigger: "blur" },
        // ],
      },
      terminalDForm: {}, //终端表单
      rptNoList: [], //类型
      rpmNoList: [], //型号
      rpiNoList: [], //商户号
      storeNoList: [], //门店
      rpstNoList: [], //收银员
      hasPayPwd:false,
      twoPwdShow:false,
      towPwdForm:{
        towPwd:''
      }
    };
  },
  computed: {
    ...mapGetters(["permission"]),
    permissionList() {
      return {
        addBtn: this.vaildData(this.permission.terminal_add, false),
        viewBtn: this.vaildData(this.permission.terminal_view, false),
        //delBtn: this.vaildData(this.permission.terminal_delete, false),
        editBtn: this.vaildData(this.permission.terminal_edit, false),
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach((ele) => {
        ids.push(ele.id);
      });
      return ids.join(",");
    }
  },
  watch: {},
  created() {
    if (this.$route.query.rpstNo) {
      this.terminalRpstNo = this.$route.query.rpstNo;
      const column = this.findObject(this.option.column, "rpstNo"); //收银员编号
      column.search = false;
      column.display = false;

      const columnName = this.findObject(this.option.column, "rpstName"); //收银员名称
      columnName.hide = true;
    } else {
      this.getCashierData();
    }

    // this.getTerminalData();
    // this.initRequest()

    this.getUserHasInfo();//是否 有二级密码
  },
  methods: {
   // 二级密码 关闭回调
    handleCloseTwoPwd(done){
      this.towPwdForm.towPwd="";
      done()
    },
    // 二级密码 确定
    twoPwdSubmit(){
      let that = this;
      this.$refs.towPwdForm.validate((valid) => {
        if (valid) {
          let param={
            payPwd:md5(that.towPwdForm.towPwd+''),
            id:that.towPwdForm.id,
            rpsNo:that.towPwdForm.rpsNo,
            rpstNo:that.towPwdForm.rpstNo
          }
          staffUNBindTerminal(param).then((res) => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: res.data.msg
            });
            that.$refs.crud.toggleSelection();
            that.twoPwdShow = false;
            that.towPwdForm.towPwd="";
          },
          (error) => {
            window.console.log(error);
          });
        } else {
          return false;
         }
      });
    },
    // 是否 有二级密码
    getUserHasInfo(){
      userHasInfo().then(res =>{
        this.hasPayPwd = res.data.data.hasPayPwd;
      }, error => {
        window.console.log(error);
      })
    },
    // 跳转用户信息页面
    toUserInfo(){
      this.$confirm('请您先设置二级密码，再操作！', '提示', {
        confirmButtonText: '确定',
        showCancelButton:false,
        type: 'warning'
      }).then(() => {
        this.$router.push({ path: '/info/index', query: { index: 2 }})
      })
    },
    /* 获取收银员列表 */
    getCashierData() {
      const rpsNo = this.$route.query.rpsNo;
      getCashierList(
        "-1",
        "-1",
        {rpsNo}
      ).then((res) => {
        this.rpstOptions = res.data.data.records;
      });
    },
    /* 获取未绑定/已绑定 终端列表*/
    getTerminalData() {
      this.terminalAllot = [];
      this.terminalData = [];
      if (this.$route.query.rpstNo) {
        let rpstNo = this.$route.query.rpstNo;
        this.getCashierBind(rpstNo);
      } else {
        let rpsNo = this.$route.query.rpsNo;
        this.getStoreBind(rpsNo);
      }
      // getStoreBindTerminalPage(
      //   "-1",
      //   "-1",
      //   rpsNo
      // ).then((res) => {
      //   let terminalAllots = res.data.data.records;
      //   terminalAllots.forEach((item) => {
      //     this.terminalAllot.push(item.rtNo);
      //   });
      // });
      
    },
    /* 门店未绑定  */
    getStoreBind(rpsNo) {
      getStoreUNBindTerminalPage("-1", "-1", rpsNo).then((res) => {
        let terminalData = res.data.data.records;
        terminalData.forEach((item, index) => {
          this.terminalData.push({
            label: item.rtName,
            key: item.rtNo,
            pinyin: item.rtName[index],
          });
        });
      });
    },
    /* 收银员未绑定  */
    getCashierBind(rpstNo) {
      getStaffUNBindTerminalPage("-1", "-1", rpstNo).then((res) => {
        let terminalData = res.data.data.records;
        terminalData.forEach((item, index) => {
          this.terminalData.push({
            label: item.rtName,
            key: item.rtNo,
            pinyin: item.rtName[index],
          });
        });
      });
    },
    /* 门店绑定终端 提交 */
    terminalSubmit() {
      this.$refs["cashierForm"].validate((valid) => {
        if (valid) {
          if (this.terminalAllot.length == 0) return this.$message({type: "warning", message: "请先绑定终端!"});
          const rpsNo = this.$route.query.rpsNo;
          let rtNo = this.terminalAllot.join(",");
          staffBindTerminal(rpsNo, this.cashierForm.rpstNo||this.$route.query.rpstNo, rtNo).then(
            () => {
              this.onLoad(this.page);
              this.terminalDialog.visible = false;
              this.$refs["cashierForm"].resetFields();
              this.$message({
                type: "success",
                message: "操作成功!",
              });
            },
            (error) => {
              window.console.log(error);
            }
          );
        }
      });
    },
    /* 终端解绑 */
    handleTerminalUN(row) {
      if(!this.hasPayPwd){
        this.toUserInfo()
      } else {
        let param = {
          id:row.id,
          rpsNo:this.$route.query.rpsNo,
          rpstNo:this.$route.query.rpstNo
        }
        Object.assign(this.towPwdForm, param)
        this.twoPwdShow = true;
      }
    },
    //查看二维码
    getqrCodeUrl(qrcodeUrl) {
      this.rqUrlImage[0] = qrcodeUrl;
      this.payVoucherDialog = true;
    },
    // 新建
    handleSave() {
      this.terminalDialog.visible = true;
      this.terminalDialog.type = "add";
      this.terminalDialog.text = "新增绑定终端";
      this.terminalDialog.disabled = false;
    },
    // 编辑
    handleEdit(row) {
      this.terminalDialog.visible = true;
      this.terminalDialog.type = "edit";
      this.terminalDialog.text = "编辑绑定终端";
      this.terminalDialog.disabled = false;
      this.terminalDForm = JSON.parse(JSON.stringify(row));
    },
    // 终端---新建弹框 关闭前回调
    dialogClose(done) {
      this.$refs["cashierForm"].resetFields();
      this.onLoad(this.page);
      done();
    },
    // 保存
    rowSave(row, done, loading) {
      add(row).then(
        () => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!",
          });
          done();
        },
        (error) => {
          loading();
          window.console.log(error);
        }
      );
    },
    rowUpdate(row, index, done, loading) {
      update(row).then(
        () => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!",
          });
          done();
        },
        (error) => {
          loading();
          window.console.log(error);
        }
      );
    },
    rowDel(row) {
      if(!this.hasPayPwd){
        this.toUserInfo()
      } else {
        this.towPwdForm.ids = row.id;
        this.twoPwdShow = true;
      }
    },
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning("请选择至少一条数据");
        return;
      }
      if(!this.hasPayPwd){
        this.toUserInfo();
      } else {
        this.towPwdForm.ids = this.ids;
        this.twoPwdShow = true;
      }
    },
    beforeOpen(done, type) {
      if (["edit", "view"].includes(type)) {
        getDetail(this.form.id).then((res) => {
          this.form = res.data.data;
        });
      }
      done();
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    onLoad(page, params = {}) {
      this.loading = true;
      if (this.$route.query.rpstNo) { //收银员进入
        getStaffBindTerminalPage(
          page.currentPage,
          page.pageSize,
          this.$route.query.rpstNo,
          Object.assign(params, this.query)
        ).then((res) => {
          const data = res.data.data;
          this.page.total = data.total;
          this.data = data.records;
          this.loading = false;
          this.selectionClear();
        });
      } else {//门店进入
        getStoreBindTerminalPage(
          page.currentPage,
          page.pageSize,
          this.$route.query.rpsNo,
          Object.assign(params, this.query)
        ).then((res) => {
          const data = res.data.data;
          this.page.total = data.total;
          this.data = data.records;
          this.loading = false;
          this.selectionClear();
        });
      }
      this.getTerminalData();
    },
    handleImport() {
      this.excelBox = true;
    },
    handleExport() {
      let exQuery = ``;
      exQuery += `&rtName=${this.search.rtName}`;
      exQuery += `&rtNo=${this.search.rtNo}`;
      exQuery += `&rptNo=${this.search.rptNo}`;
      exQuery += `&rpmNo=${this.search.rpmNo}`;
      // exQuery += `&rsSn=${this.search.rsSn}`;
      exQuery += `&rpiNo=${this.search.rpiNo}`;
      exQuery += `&storeNo=${this.search.storeNo}`;
      exQuery += `&rpstNo=${this.search.rpstNo}`;
      exQuery += `&rtPara=${this.search.rtPara}`;
      exQuery += `&isOn=${this.search.isOn}`;
      this.$confirm("是否导出用户数据?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        window.open(
          `/api/rb-service/service/terminal/terminal/export?${
            this.website.tokenHeader
          }=${getToken()}` + exQuery
        );
      });
    },
    handleTemplate() {
      window.open(
        `/api/rb-service/service/terminal/terminal/export-template?${
          this.website.tokenHeader
        }=${getToken()}`
      );
    },
    uploadAfter(res, done) {
      this.excelBox = false;
      this.refreshChange();
      done();
    },
    sortChange(val) {
      if (val.order == "ascending") {
        //正序
        this.query.ascs = val.prop;
        this.query.descs = "";
      } else {
        //倒序
        this.query.descs = val.prop;
        this.query.ascs = "";
      }
      this.refreshChange();
    }
  },
};
</script>

<style lang="scss" scoped>
/deep/.el-transfer-panel__list.is-filterable {
  width: 400px !important;
  height: 500px !important;
}

/deep/.el-transfer-panel {
  width: 400px !important;
  height: 500px !important;
}

.cashier-box {
  // padding: 0 20px;
  margin-bottom: 20px;
}
</style>
